<template>
    <div class="video-wrapper">
        <div v-if="warnTip" class="error-tip">{{ warnTip }}</div>
        <div class="video-player" :id="playerId">
            <!-- <div class="video-pause-mask"></div> -->
            <div v-if="isShowTime" class="video-time">{{fmtVideoTime(videoTime)}}</div>
        </div>
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref, onBeforeUnmount, computed, onUnmounted, watch } from 'vue';
import XgPlayer from '@/components/.xgplayer/xgplayer.js';
import { useRoute } from 'vue-router';
import useReport from '@/hooks/useReport.js';
import { fmtTime } from '@/lib/biz-tools.js';
import { useStore } from 'vuex';
import { decSub } from '@/lib/tools'

const store = useStore();

const route = useRoute();

const report = useReport();

const emit = defineEmits(['create-notes', 'set-duration']);


const videoObj = ref({});

const props = defineProps({
    playerId: {
        type: [String, Number],
        default: 'player' 
    },
    videoData: {
        type: Object,
        default: () => { 
            return {}
        }
    },
    detail: {
        type: Object,
        default: () => {
            return {}
        }
    },
    isPreviewType: { // 是否是预览模式
        type: Boolean,
        default: false
    },
    isReport: { // 是否需要发心跳
        type: Boolean,
        default: true
    },
    videoConfig: { // 视频配置
        type: Object,
        default: () => {
            return {}
        } 
    },
    height: {
        type: String,
        default: '458px' 
    },
    isShowTime: {
        type: Boolean,
        default: false
    }
})

const userAndDetail = computed(() => {
    return {currentUser: store.state.currentUser, detail: props.detail};
})

const currentUser = computed(() => {
    return store.state.currentUser;
})

const detail = computed(() => {
    return props.detail || {};
})

// watch(() => userAndDetail.value, async(val) => {
//     await nextTick();
//     console.log('开始初始化', val.detail?.courseWareId);
//     if(val?.currentUser?.userId && val?.detail?.courseWareId) {
//         getVideoRecord(val.currentUser.userId, val.detail.courseWareId);
//     }
// }, {deep: true, immediate: true})


const warnTip = ref('');

const historyLocation = ref(0);

const videoTime = ref(null);


let player = null;

let isInit = true;

function initPlayer () {
    isInit = true;
    videoObj.value = Object.assign({
        autoplay: true,
        el: document.querySelector(`#${props.playerId}`),
        url: props.videoData.transferFileUrl || props.videoData.materialUrl,
        poster: props.videoData.snapshotCover,
        fluid: true,
        closeFocusVideoFocus: true,
        closePlayVideoFocus: true,
        definitionActive: 'hover',
        volume: 0.3,
        textTrack: props.detail.textTrack || [],
    }, props.videoConfig);
    videoTime.value = props.videoData.duration;
    console.log('定位开始')
    if(props.isReport && historyLocation.value) {
        let startDot = { time: historyLocation.value, text: '上一次播放位置' };
        videoObj.value.progressDot = [startDot];
        videoObj.value.lastPlayTime = historyLocation.value;
    }
   
    // // 初始化的时候有心跳记录
    // if (props.isReport && historyLocation.value) {
    //     if(historyLocation.value >= videoTime.value){
    //         let computedTime = videoTime.value - 5
    //         historyLocation.value = computedTime > 0 ? computedTime : 0
    //     }
    //     console.log('有历史记录', historyLocation.value)
    //     let startDot = { time: historyLocation.value, text: '上一次播放位置' };
    //     videoObj.value.progressDot = [startDot];
    //     videoObj.value.lastPlayTime = historyLocation.value;
    // }
    player = new XgPlayer(videoObj.value);
    player.player.once('complete', () => {
        setTimeout(() => {
            // 视频总时长
            let duration = player?.player?.duration;
            if (props.videoData?.resourceStart > duration) {
                warnTip.value = '检测到视频已更换'
            } else {
                warnTip.value = '';
            }
            videoTime.value = duration;
            emit('set-duration',{playerId: props.playerId, duration});
        }, 500);
    })
    if(props.isReport) { // 是否需要发心跳
        videoStateListener();
    }
}



// 视频监听
function videoStateListener () {
    setTimeout(() => {
        if (player?.player) {
            player.player.on('play', () => {
                console.log('play');
                report.startWatchTime();
                if(isInit) {
                    watchVideoSeek();
                }
            })
            // 
            // player.player.on('ended', () => {
            //     console.log('ended');
            //     report.endWatchTime();
            //     report.hbReport(player.player.currentTime);
            // })
            //
            player.player.on('pause', (e) => {
                console.log('pause');
                report.endWatchTime();
                if (props.isReport && props.videoData.materialStatus === 'usable') {
                    report.hbReport(player.player.currentTime);
                }
                player?.player && player.player.once('play', () => {
                    player.player.play();
                })
            })

            player.player.on('error', (error) => {
                report.endWatchTime();
            })
        }
    })
}

// 定时判断当前视频是否在播
let timer = null;
// 监听视频是否在卡的状态
function watchVideoSeek() {
    isInit = false;
    timer = setInterval(() => {
        if (!player?.player?.isSeeking) {
            clearAll();
            return;
        }
        if(player?.player) {
            player.player.currentTime =  player.player.currentTime > 1 && player.player.currentTime - 1 || 0;
        }
    }, 1000);
}

function clearAll() {
    timer && window.clearInterval(timer);
}


function startVideo (item) {
    if (item.resourceStart > player.player.duration) {
        G_dispatchEvent('toast', { message: '检测到音视频已更换', type: 'error' });
        return;
    }
    if (!player.player.ended) {
        player.pause();
    }
    // 删除标记
    player.player.removeAllProgressDot();
    player.player.currentTime = item.resourceStart;
    if (item.noteType === 1) {
        player.player.addProgressDot(item.resourceStart);
        player.player.addProgressDot(item.resourceEnd);
        let duration = item.resourceEnd - item.resourceStart;
        player.player.addProgressDot(item.resourceStart, duration, { background: 'red' });
    } else {
        player.player.addProgressDot(item.resourceStart);
    }
}



async function startRecord (onlineState = '') {
    await nextTick();
    let time = player?.player?.currentTime || 0;
    return await report.reportFn(route.params.moocId, props.detail.courseWareId, time, onlineState);
}

function getVideoRecord(userId, resId) {
    G_transmit('hbUserRecord', {
        queries: {
            appId: '100002',
            bizId: route.params.moocId,
            bizType: 'mooc',
            srxUserId: userId,
            resId: resId,
            resSource: 'courseWare'
        },
        silence: true
    }).then((res) => {
        let watchLocation = res.data?.watchLocation || 0;
        historyLocation.value = watchLocation;
        if(historyLocation.value >= props.videoData.duration){
            let computedTime = props.videoData.duration - 5
            historyLocation.value = computedTime > 0 ? computedTime : 0
        }
        if (props.videoData.materialStatus === 'usable') { // 资源可用
            initPlayer();
        }
    })
}

// 设置字幕
function setSubTitle(subList) {
    if(player?.player) {
        player.player.setSubTitles(subList);
    }
}

// 结束心跳 销毁视频
function destroyVideo () {
    player && player.pause();
    player && player.destroy(false);
    if(props.isReport) {
        // report.endWatchTime();
        report.endReportFn();
    }
}

// 格式化时间
function fmtVideoTime(val = 0) {
    return fmtTime(val);
}

onMounted(async () => {
    // await nextTick();
    // if (props.videoData.materialStatus === 'usable') { // 资源可用
    //     initPlayer();
    // }
    await nextTick();
    if(currentUser.value?.userId && detail.value?.courseWareId) {
        getVideoRecord(currentUser.value.userId, detail.value.courseWareId);
    }
})

onBeforeUnmount(() => {
    clearAll();
    destroyVideo();
})

onUnmounted(() => {

})

defineExpose({
    startVideo,
    startRecord,
    setSubTitle,
    initPlayer,
    destroyVideo
})

</script>

<style lang="scss" scoped>
:deep(.xgplayer-skin-eoc .xgplayer-progress-played) {
    background: var(--main-active-text-color);
}

:deep(.xgplayer-controls) {
    transition: all 0.2s;
    background: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.6000) 100%);
}

:deep(.xgplayer-progress-tip) {
    word-break: break-all;
    white-space: normal !important;
    overflow-y: auto;
    min-width: 140px !important;
    max-height: 200px !important;
    overflow-y: auto;
    padding: 10px 10px;
    border: none !important;
    font-size: 12px;
    box-shadow: 0px 4px 16px 0px rgb(11 23 73 / 10%);
    border-radius: 4px !important;
    color: #ffffff !important;
    background: rgba(0, 0 ,0 , 0.7) !important;
}

.show-slider {
    :deep(.xgplayer-controls) {
        bottom: -78px;
        background: transparent;
        display: flex;
    }
}

.video-wrapper {
    position: relative;

    .error-tip {
        color: var(--srt-color-danger);
    }

    .video-player {
        height: 458px;
        width: 100%;
    }
    // .video-pause-mask {
    //     display: none;
    // }
    // .xgplayer-pause {
    //     .video-pause-mask {
    //         display: block;
    //         background: rgba(0, 0, 0, 0.5);
    //         position: absolute;
    //         left: 0;
    //         top: 0;
    //         width: 100%;
    //         height: 100%;
    //         z-index: 101;
    //     }
    // }
    .video-time {
        position: absolute;
        color: #ffffff;
        font-size: 14px;
        right: 8px;
        bottom: 4px;
        line-height: 22px;
        z-index: 102;
    }
}
</style>